//
//  Sqlite3Helper.m
//  NetTest
//
//  Created by mac on 12-5-12.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "Sqlite3Helper.h"

#define DBFileName @"dbTicket.db"

@implementation Sqlite3Helper

static Sqlite3Helper *_Instance;

+(Sqlite3Helper*)Instance{
    if (_Instance ==nil) {
        _Instance=[[Sqlite3Helper alloc] init];
    }
    return _Instance;
}

static int openCount=0;

-(id)init{
    if ([super init]) {
        openResult=-1;
    }
    return self;
}

- (NSString *)getDBFilePahth {
    //find file path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    NSString *dbPath = [documentsDir stringByAppendingPathComponent:DBFileName];
    openCount++;
    FCLOG(@"dbPath = %@",dbPath);
    return dbPath;
}

-(void) copyDatabaseIfNeeded {
    //Using NSFileManager we can perform file system operations.
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;

    NSString *dbPath = [self getDBFilePahth];
    BOOL success = [fileManager fileExistsAtPath:dbPath];
    
    if(!success) {
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DBFileName];
        success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
        
        if (!success)
            NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}


-(void)executeNonQuery:(NSString *)sql{
   
    if (openResult!=SQLITE_OK) {
        [self openDB];
    }
    char *error;
    if (openResult==SQLITE_OK) {
        FCLOG(@"Open Db Success");
        
        if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &error )!= SQLITE_OK)
        {
            NSAssert(0, @"Error: Can't Execute by Sql = %@ Open Count = %i", sql,openCount);
        }
        if (error!=NULL) {
            sqlite3_free(error);
        }
    }
    else{
        NSAssert(0, @"Error:Can't Open DBFile Result = %i, Open Count",openResult,openCount);
    }
//    sqlite3_close(db);
}

-(void)openDB{
//    sqlite3 *db;
    if (openResult==SQLITE_OK) {
        [self closeDB];
    }
    
    NSString *dbPath;
    dbPath = [self getDBFilePahth];
    openResult=sqlite3_open([dbPath UTF8String], &db);
    
    if (openResult==SQLITE_OK) {
        
    }
    else{
        [self closeDB];
        openResult=sqlite3_open([dbPath UTF8String], &db);
    }
}

-(void)closeDB{
    sqlite3_close(db);
    openResult = -1;
}

-(sqlite3_stmt *)execQuery:(NSString *)sql{
    
    sqlite3_stmt *statement = nil;
    if (openResult!=SQLITE_OK) {
        [self openDB];
    }
    if (openResult==SQLITE_OK) {
        FCLOG(@"Open Db Success");
        int exeResult=sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, NULL);
         if ( exeResult!= SQLITE_OK)
         {
             NSAssert(0, @"Error: ExeResult = %i, Can't Execute by Sql = %@ open Count = %i",exeResult, sql,openCount);
         }
        //sqlite3_free(error);
    }
    else{
//        char *error=NULL;
//        
//        sqlite3_file_control(db, "main", SQLITE_LAST_ERRNO, error);
        
        NSAssert(0, @"Error:Can't Open DBFile openResult = %i, open Count = %i",openResult,openCount);
        
//        if (error!=NULL) {
//            sqlite3_free(error);
//        }
    }
    
    return statement;
}

-(void)close{
    [self closeDB];
}

@end
